package com.iiapk.grid.database;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.iiapk.gridnew.domain.Article;

/**
 * @author hey
 * 管理地址数据库
 */
public class ArticleManager {

	private Context context;
	private static final String TABLE_NAME = Article.TABLE_NAME;
	
	public ArticleManager(Context context) {
		this.context = context;
	}
	
	public synchronized void close() {
		SQLiteHelper.getInstance(context).getWritableDatabase().close();
	}
	
	public synchronized SQLiteDatabase getWritableDatabase(){
		return SQLiteHelper.getInstance(context).getWritableDatabase();
	}
	
	public synchronized SQLiteDatabase getReadableDatabase(){
		return SQLiteHelper.getInstance(context).getReadableDatabase();
	}
	
	public List<Article> select(String columnId){
		List<Article> list = new ArrayList<Article>();
		SQLiteDatabase db=this.getReadableDatabase();
	    Cursor cur=db.query(TABLE_NAME, null, null, null, null, null,"id desc");
	    for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext()){
		     String title = cur.getString(cur.getColumnIndex(Article.COLUMN_TITLE));
		     String time = cur.getString(cur.getColumnIndex(Article.COLUMN_TIME));
		     String image = cur.getString(cur.getColumnIndex(Article.COLUMN_IAMGE));
		     String content = cur.getString(cur.getColumnIndex(Article.COLUMN_CONTENT));
		     String belong = cur.getString(cur.getColumnIndex(Article.COLUMN_BELONGTO));
		     String id = String.valueOf(cur.getInt(0));
		     list.add(new Article(id,title,content,time,image,belong));
		 }
	    cur.close();
	    return list; 
	}
	    
	public long insert(Article article){
		SQLiteDatabase db=this.getWritableDatabase();
	    ContentValues cv=new ContentValues(); 
	    cv.put(Article.COLUMN_ID, article.id);
	    cv.put(Article.COLUMN_TITLE, article.title);
	    cv.put(Article.COLUMN_CONTENT, article.content);
	    cv.put(Article.COLUMN_TIME, article.createTime);
	    cv.put(Article.COLUMN_IAMGE, article.image);
	    long row=db.insert(TABLE_NAME, null, cv);
	    return row;
	}
	    
	public void delete(String id){
	    SQLiteDatabase db=this.getWritableDatabase();
	    String where=Article.COLUMN_ID+"=?";
	    String[] whereValue={id};
	    db.delete(TABLE_NAME, where, whereValue);
	}
	
	public void update(Article article){
		SQLiteDatabase db=this.getWritableDatabase();
		String where=Article.COLUMN_ID+"=?";
	    String[] whereValue={article.id};
	    ContentValues cv=new ContentValues(); 
	    cv.put(Article.COLUMN_TITLE, article.title);
	    cv.put(Article.COLUMN_CONTENT, article.content);
	    cv.put(Article.COLUMN_TIME, article.createTime);
	    cv.put(Article.COLUMN_IAMGE, article.image);
	    db.update(TABLE_NAME, cv, where, whereValue);      
	}		    
	
}
